package com.fsnbigdata.web;

import com.fsnbigdata.domain.ZhDiversityReport;
import com.fsnbigdata.service.api.DiversityReportService;
import com.fsnbigdata.util.RichHtmlHandler;
import com.fsnbigdata.util.WordHtmlGeneratorHelper;
import com.fsnbigdata.util.WordUtils;
import com.hp.hpl.jena.util.ResourceUtils;
import freemarker.core.ParseException;
import freemarker.template.Configuration;
import freemarker.template.MalformedTemplateNameException;
import freemarker.template.Template;
import freemarker.template.utility.StringUtil;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Administrator on 2018/9/15.
 */
@RestController
@RequestMapping("/api")
public class WordGeneratorWithFreemarker {

    @Autowired
    private DiversityReportService diversityReportService;

    private static Configuration configuration = null;

    static {
        configuration = new Configuration(Configuration.VERSION_2_3_23);
        configuration.setDefaultEncoding("utf-8");
        configuration.setClassicCompatible(true);

    }

    public void downLoad(String filePath, HttpServletRequest request,HttpServletResponse response, boolean isOnLine) throws Exception {
        File f = new File(filePath);
        if (!f.exists()) {
            response.sendError(404, "File not found!");
            return;
        }
        BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
        byte[] buf = new byte[1024];
        int len = 0;

        response.reset(); // 非常重要
        if (isOnLine) { // 在线打开方式
            URL u = new URL("file:///" + filePath);
            response.setContentType(u.openConnection().getContentType());
            response.setHeader("Content-Disposition", "inline; filename=" + f.getName());
            // 文件名应该编码成UTF-8
        } else { // 纯下载方式
            response.setContentType("application/x-msdownload");
            //设置火狐浏览器下载问题
            if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > -1)
            {
                response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + f.getName());
            }else {
                response.setHeader("Content-Disposition", "attachment; filename=" + f.getName());
            }
        }
        OutputStream out = response.getOutputStream();
        while ((len = br.read(buf)) > 0){
            out.write(buf, 0, len);
        }
        br.close();
        out.close();

        File file=new File(filePath);
        if(file.exists()&&file.isFile()){
            file.delete();
        }
    }


    /**
     * 生成附件
     * @param request
     * @param response
     * @throws Exception
     */
    @GetMapping("accessory")
    public void accessory(HttpServletRequest request,HttpServletResponse response) throws Exception{
        String id = request.getParameter( "id" );
        String sign = request.getParameter( "sign" );
        ZhDiversityReport zhDiversityReport = diversityReportService.findById( Long.parseLong( id ) );
        HashMap<String, Object> data = new HashMap<String, Object>();
        List<String> accessory = diversityReportService.getAccessory(zhDiversityReport.getProvince(),zhDiversityReport.getCity(),zhDiversityReport.getCounty(),sign);

        RichHtmlHandler handler = new RichHtmlHandler(accessory.get( 1 ));
        handler.setDocSrcLocationPrex("file:///C:/8595226D");
        handler.setDocSrcParent("file3405.files");
        handler.setNextPartId("01D214BC.6A592540");
        handler.setShapeidPrex("_x56fe__x7247__x0020");
        handler.setSpidPrex("_x0000_i");
        handler.setTypeid("#_x0000_t75");
        handler.handledHtml(false);
        String bodyBlock = handler.getHandledDocBodyBlock();

        String handledBase64Block = "";
        if (handler.getDocBase64BlockResults() != null
                && handler.getDocBase64BlockResults().size() > 0) {
            for (String item : handler.getDocBase64BlockResults()) {
                handledBase64Block += item + "\n";
            }
        }
        data.put("imagesBase64String", handledBase64Block);

        String xmlimaHref = "";
        if (handler.getXmlImgRefs() != null
                && handler.getXmlImgRefs().size() > 0) {
            for (String item : handler.getXmlImgRefs()) {
                xmlimaHref += item + "\n";
            }
        }

        data.put("imagesXmlHrefString", xmlimaHref);
        data.put("content", bodyBlock);
        String fileName = accessory.get( 0 )+".doc";
        fileName = URLEncoder.encode(fileName,"UTF-8");

        String s = new File("").getCanonicalPath();
        s = s+"\\files";

        File file =new File(s);
        //如果文件夹不存在则创建
        if  (!file .exists()  && !file .isDirectory())
        {
            file.mkdir();
        }

        String url = s+"/"+fileName;
        new WordUtils().createWord(data,url);
        File f = new File(url);
        downLoad(url,request,response,false);
    }

    /**
     * 导出
     * @param request
     * @param response
     * @throws Exception
     */
   @GetMapping(value = "export")
   public void getContent(HttpServletRequest request, HttpServletResponse response) throws Exception {
       HashMap<String, Object> data = new HashMap<String, Object>();
       ZhDiversityReport zhDiversityReport = diversityReportService.findById(Long.parseLong(request.getParameter("id")));
       RichHtmlHandler handler = new RichHtmlHandler(zhDiversityReport.getContent());
       handler.setDocSrcLocationPrex("file:///C:/8595226D");
       handler.setDocSrcParent("file3405.files");
       handler.setNextPartId("01D214BC.6A592540");
       handler.setShapeidPrex("_x56fe__x7247__x0020");
       handler.setSpidPrex("_x0000_i");
       handler.setTypeid("#_x0000_t75");
       handler.handledHtml(false);
       String bodyBlock = handler.getHandledDocBodyBlock();

       String handledBase64Block = "";
       if (handler.getDocBase64BlockResults() != null
               && handler.getDocBase64BlockResults().size() > 0) {
           for (String item : handler.getDocBase64BlockResults()) {
               handledBase64Block += item + "\n";
           }
       }
       data.put("imagesBase64String", handledBase64Block);

       String xmlimaHref = "";
       if (handler.getXmlImgRefs() != null
               && handler.getXmlImgRefs().size() > 0) {
           for (String item : handler.getXmlImgRefs()) {
               xmlimaHref += item + "\n";
           }
       }

       data.put("imagesXmlHrefString", xmlimaHref);
       data.put("content", bodyBlock);
       String fileName = zhDiversityReport.getTitle()+".doc";
       fileName = URLEncoder.encode(fileName,"UTF-8");

       String s = new File("").getCanonicalPath();
       s = s+"\\files";

       File file =new File(s);
        //如果文件夹不存在则创建
       if  (!file .exists()  && !file .isDirectory())
       {
           file.mkdir();
       }

       String url = s+"/"+fileName;
       new WordUtils().createWord(data,url);
       File f = new File(url);
       downLoad(url,request,response,false);
//       WordGeneratorWithFreemarker.createDoc(data, "model/file3405.ftl",response, url,fileName);

   }

}
